package com.hwg.shiliupro.interceptor;


import com.hwg.shiliupro.exception.Exception401;
import com.hwg.shiliupro.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.stream.Stream;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
//拦截器先拦住校验token  再到aop权限校验
    @Value("${interceptor.pass}")
    private String[] interceptorPass;
//    private String[] interceptorPass = {"/api/login","/api/login/checkCode"};

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if("OPTIONS".equals(request.getMethod()) ||
                Stream.of(interceptorPass).anyMatch(p->p.equals(request.getRequestURI()))){
            //无需校验的白名单/OPTIONS请求(因为该请求header中不会携带cookie或者token)  直接放行
            log.info("直接放行");
            return true;
        }
        //获取token进行校验
        String jwtToken = request.getHeader("Authorization");
        if(!JwtUtils.checkToken(jwtToken)){
            //校验失败  全局异常处理器再对他进行处理和结果返回
            log.info("token不存在/校验token失败");
            throw new Exception401(401,"token不存在/校验token失败");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
